package com.system.boot.file.controller;

import com.system.api.SuperInterface;
import com.system.api.file.entity.FileAvatar;
import com.system.boot.file.service.FileAvatarService;
import com.system.common.constant.SystemConstant;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.yang.common.core.exception.BaseException;
import org.yang.common.core.result.BaseController;
import org.yang.common.core.result.R;
import org.yang.common.i18n.enums.RI18nEnum;
import org.yang.database.minio.constant.MinioConstant;
import org.yang.database.minio.utils.MinioUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 头像文件
 * @author: lslands
 * @description:   
 * @version：v1.0
 * @date:    2024/6/29 23:55
 */
@Slf4j
@RestController
@RequestMapping("/file-avatar")
@RequiredArgsConstructor
public class FileAvatarController extends BaseController {

    private final FileAvatarService fileAvatarService;
    private final MinioUtils minioUtils;

    /**
     * 头像上传方法
     * @param file 文件内容
     * @return Map<String,String>  {avatarId:'头像id',yangName:'新头像名称',bucketName:'桶名称'}
     */
    @PostMapping("/uploadAvatar")
    public R<Map<String,String>> uploadAvatar(MultipartFile file){
        String yangName = null;
        try{
            Map<String, String> resultMap = minioUtils.uploadMapFileSingle(SystemConstant.AVATAR_BUCKET, file);
            yangName=  resultMap.get(MinioConstant.YOUNG_FILE_NAME);
            String oldName=  resultMap.get(MinioConstant.OLD_FILE_NAME);
            FileAvatar build = FileAvatar.builder()
                    .oldFileName(oldName).youngFileName(yangName).bucketName(SystemConstant.AVATAR_BUCKET)
                    .build();
            Long avatarId = fileAvatarService.handInsert(build);
            Map<String,String> stringStringMap=new HashMap<>();
            stringStringMap.put("avatarId", avatarId.toString());
            stringStringMap.put("bucketName", SystemConstant.AVATAR_BUCKET);
            stringStringMap.put(MinioConstant.YOUNG_FILE_NAME,yangName);
            return R.success(RI18nEnum.UPLOAD, stringStringMap);
        }catch (RuntimeException e){
            return R.fail(RI18nEnum.FAIL);
        }catch (BaseException e){
            minioUtils.remove(SystemConstant.AVATAR_BUCKET,yangName);
            //执行文件删除
            return R.fail(RI18nEnum.FAIL);
        }
    }

}
